package com.sinosoft.gateway.filter;

import java.nio.charset.StandardCharsets;
import java.util.function.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 不进行处理的连接
 *
 * @Auther: zouren
 * @Date: 2019/2/26 15:27
 * @Description:
 */
@Component
public class IgnoredGlobalFilter implements GlobalFilter, Ordered {
    
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    GProperties g;
    private AntPathMatcher ant = new AntPathMatcher();
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        
        if (exchange.getAttributes().containsKey("IgnoredGlobalFilter")) {
            logger.error("Illegal Access Attempt Detected !!" + exchange.getRequest().getRemoteAddress().getAddress() + "   !!" + exchange.getRequest().getURI());
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            byte[] bytes = "Illegal Access Attempt Detected !!".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Mono.just(buffer));
        }
        boolean lambda = g.fetchIgnored().stream().anyMatch(r -> ant.match(r, exchange.getRequest().getURI().getPath()));
        if (lambda) {
            logger.warn("监控:  " + exchange.getRequest().getRemoteAddress().getAddress() + "  @@@@@@   " + exchange.getRequest().getURI());
            exchange.getAttributes().put("IgnoredGlobalFilter", "@actuator");
            
        }
        return chain.filter(exchange);
    }
    
    @Override
    public int getOrder() {
        return 0;
    }
}
